<script setup>
import RichTextEditor from '../../components/RichTextEditor.vue';
import { defineAsyncComponent, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router';
import getRequest, {downloadFiles} from '../../utils/lxw_request';

// rich text editor config 
const my_practice_text = ref('')
function textChange(newValue) {
    my_practice_text.value = newValue
}

// add appendix file
const add_appendix_file_ref = ref(null)
const add_img_top = ref(160)

const add_file_input_ref = ref(null)
const fileList = ref([])
function openFileExplorer(e) {
    e.stopPropagation();
    add_file_input_ref.value.click();

}

function addFiles() {
    const list = []
    for (let i = 0; i < add_file_input_ref.value.files.length; i++) {
        list.push(add_file_input_ref.value.files[i])
    }
    fileList.value = list.map(x => x)
}

function deleteFile(index) {
    fileList.value = fileList.value.filter((e, i) => i != index)
}

// Modal
const HistorySubmissionModal = defineAsyncComponent(() => import('../../components/HistorySubmissionModal.vue'))
const MyScoresModal = defineAsyncComponent(() => import('../../components/MyScoresModal.vue'))
const SubmitWorkModal = defineAsyncComponent(() => import('../../components/SubmitWorkModal.vue'))
const isOpenModal = ref(false)
const modalName = ref('')
function openModal(name) {
    isOpenModal.value = true;
    modalName.value  = name;
}
function closeModal() {
    isOpenModal.value = false

}







onMounted(() => {
    add_appendix_file_ref.value !== null ? add_appendix_file_ref.value.addEventListener('scroll', (e) => {
        // 160是添加附件图片到顶部的距离
        add_img_top.value = e.target.scrollTop + 160
    }) : {} ;
})


// API
const router = useRouter();
const course_id = router.currentRoute.value.params['subject_id']
const course = ref(null)
getCourse();


function getCourse() {
    getRequest(`/stu/course/${course_id}`, "GET", new Headers({ 'Content-Type': 'application/json' }))
        .then((response) => response.json())
        .then((json) => {
            if (json.code === 200) {
                course.value = json.data;
            } else {
                alert(json.msg);
            }
        })
        .catch((err) => {
            console.error(err);
        })
}

function submitLog() {
    const formData = new FormData();

    formData.append("text", my_practice_text.value);

    for(const file of add_file_input_ref.value.files) {
        formData.append("files", file);
    }

    getRequest(`/stu/course/${course_id}/logs`, "POST", new Headers(), formData)
        .then((response) => response.json())
        .then((json) => {
            if (json.code === 200) {
                alert("提交日志成功")
                getCourse();
                fileList.value = [];
                my_practice_text.value = "";
            } else {
                alert(json.msg);
            }
        })
        .catch((err) => {
            console.error(err);
        })
}



// iterates course['courseCatalogue']

function getStringFromCourseCatalogue(obj, level) {
    let str = "";
    for(const property in obj) {
        str += "&ensp;&ensp;&ensp;&ensp;".repeat(level) + property + ": ";
        if(typeof obj[property] === "object") {
            str += "<br/>" + getStringFromCourseCatalogue(obj[property], level+1);
        } else {
            str += `${obj[property]}<br/>`
        }
    }

    return str;
}



</script>
<template>
    <div class="my-practice-container">
        <div class="my-practice" v-if="course != null" >
            <div class="title_and_scores">
                <p>{{ course['courseName'] }}</p>
                <div class="buttons" >
                    <button type="button" @click="openModal('my_scores')">查看成绩</button>
                    <button type="button" @click="openModal('submit_work')" >提交实践作品</button>
                </div>
            </div>
            <p>步骤</p>
            <div class="requirement-container" v-html="getStringFromCourseCatalogue(course['courseCatalogue'], 1)" >
                
            </div>
            <p>附件</p>
            <div class="appendix-file">
                <ul>
                    <li v-for="file in course['files']"><span class="file-link" @click="downloadFiles(file['fileId'], file['fileName'])" >{{ file['fileName'] }}</span></li>

                </ul>
            </div>
            <!-- <div class="teacher_evaluation">
                <p>老师评语</p>
                <button>详情</button>
            </div>
            <div class="teacher_evaluation-container">
                Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean euismod bibendum laoreet. Proin gravida
                dolor sit amet lacus
                accumsan et viverra justo commodo. Proin sodales pulvinar sic tempor. Sociis natoque penatibus et magnis
                dis parturient
                montes, nascetur ridiculus mus. Nam fermentum, nulla luctus pharetra vulputate, felis tellus mollis
                orci, sed rhoncus pronin
                sapien nunc accuan eget.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean euismod bibendum
                laoreet. Proin Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean euismod bibendum laoreet.
                Proin gravida dolor sit amet lacus
                accumsan et viverra justo commodo. Proin sodales pulvinar sic tempor. Sociis natoque penatibus et magnis
                dis parturient
                montes, nascetur ridiculus mus. Nam fermentum, nulla luctus pharetra vulputate, felis tellus mollis
                orci, sed rhoncus pronin
                sapien nunc accuan eget.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean euismod bibendum
                laoreet. Proin
            </div> -->
            <div>
                <p>日志</p>    
            </div>
            <RichTextEditor class="rich-text-editor" v-model:text="my_practice_text" />
            <p>添加附件</p>
            <div class="add-appendix-file" ref="add_appendix_file_ref">
                <ul>
                    <li v-for="(file, index) in fileList" :key="index">{{ file.name }}<img
                            src="/src/assets/images/student/close.svg" alt="Delete" @click="deleteFile(index)" /></li>

                </ul>
                <img src="/src/assets/images/student/file-add.svg" alt="File add" width="32" height="32"
                    :style="{ top: add_img_top + 'px' }" @click="openFileExplorer" />
                <input type="file" ref="add_file_input_ref" style="display: none;" multiple @change="addFiles" />
            </div>
            <div class="buttons-container">
                <button type="button" @click="openModal('history_submission')">查看历史提交</button>
                <div class="right-buttons">
                    <!-- <button>保存</button> -->
                    <button type="button" style="background-color: #8493a6; color: #ffffff;" @click="() => submitLog()" v-if="(new Date(course['endDate'])).getTime() > (new Date()).getTime()" >提交</button>
                </div>
            </div>
        </div>
        <MyScoresModal v-if="isOpenModal && modalName == 'my_scores'" v-model:is-open-modal="isOpenModal" />
        <HistorySubmissionModal  v-if="isOpenModal && modalName == 'history_submission'" v-model:is-open-modal="isOpenModal" />
        <SubmitWorkModal  v-if="isOpenModal && modalName == 'submit_work'" v-model:is-open-modal="isOpenModal"   />
    </div>


</template>
<style scoped>
.my-practice-container {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
}

.my-practice {
    background-color: #ffffff;
    border-radius: 10px;
    box-shadow: 0px 3px 6px 0px rgba(0, 0, 0, 0.16);
    width: 1057px;
    /* height: 662px; */
    padding: 31px;
    margin: 50px 0;

}

.my-practice p {
    font-family: Source Han Sans CN;
    color: #707070;
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 6px;
}

.my-practice p::after {
    content: ": ";
}

.my-practice .title_and_scores,
.my-practice .teacher_evaluation,
.my-practice .buttons-container {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 20px;
}

.my-practice .title_and_scores p,
.my-practice .teacher_evaluation p {
    font-size: 30px;
    margin: 0;
}

.my-practice .title_and_scores p::after {
    content: ''
}

.title_and_scores .buttons button {
    margin-left: 20px;
}

.my-practice button {
    width: 120px;
    height: 36px;
    background-color: #8493a6;
    box-shadow: 0px 3px 6px 0px rgba(0, 0, 0, 0.16);
    border: none;
    border-radius: 6px;
    color: #fafafa;
    text-align: center;
    cursor: pointer;
    line-height: 36px;
    font-size: 18px;
    padding: 0;
    font-family: Source Han Sans CN;
    user-select: none;
}

.my-practice button:hover {
    opacity: 0.85;
}

.my-practice button:active {
    transform: translateY(3px);
}

.my-practice .requirement-container,
.my-practice .teacher_evaluation-container {
    height: 144px;
    border: 1px solid #707070;
    padding: 12px;
    overflow: auto;
    color: #707070;
    font-size: 16px;
    line-height: 27px;
    margin-bottom: 20px;
}

.my-practice .appendix-file,
.my-practice .add-appendix-file {
    height: 200px;
    border: 1px solid #707070;
    padding: 12px;
    overflow: auto;
    margin-bottom: 25px;
}

.my-practice .appendix-file>ul>li,
.my-practice .add-appendix-file>ul>li {
    list-style: none;
    height: 32px;

}

.my-practice .appendix-file>ul>li::before,
.my-practice .add-appendix-file>ul>li::before {
    content: url("/src/assets/images/student/file.svg");
    vertical-align: middle;
}

.my-practice .add-appendix-file>ul>li img {
    vertical-align: middle;
    margin-right: 50px;
    display: inline-block;
    transform: scale(0.6);
    cursor: pointer;
}

.file-link {
    display: inline-block;
    text-decoration: underline;
    color: #0000EE;
    cursor: pointer;
    opacity: 0.7;
}

.file-link:hover {
    opacity: 1;
}

.file-link:visited {
    color: #872bff;
}

.my-practice .add-appendix-file {
    position: relative;

}

.my-practice .add-appendix-file img {

    position: absolute;
    right: 5px;
    cursor: pointer;
}

.my-practice .teacher_evaluation {
    margin-bottom: 6px;
}

.my-practice .teacher_evaluation p {
    font-size: 20px;
}

.my-practice .rich-text-editor {
    border: 1px solid #ccc;
    margin-bottom: 20px;
}

.my-practice .buttons-container .right-buttons {
    display: flex;
    align-items: center;
    justify-content: end;
    width: 271px;
}

.my-practice .buttons-container .right-buttons button:first-child {
    background-color: #ecedf0;
    color: #707070;
}

.my-practice-container .modal {
    display: none;
    width: 100%;
    height: 100%;
    position: fixed;
    top: 0;
    right: 0;
    background-color: rgba(0, 0, 0, 0.5);
    overflow: auto;
    z-index: 15;
}

.my-practice-container .modal.open {
    display: block;
}

.my-practice-container .modal .modal-content-container {
    display: flex;
    width: 100%;
    /* height: 100%;*/
    justify-content: center;
    align-items: center;
}


.my-practice-container .modal .modal-content-container .modal-content {
    width: 837px; 
	/*height: 491px;*/
    background-color: #ffffff;
    border: none;
	box-shadow: 0px 3px 6px 0px rgba(0, 0, 0, 0.16);
    padding: 20px;
    margin: 50px 0;
}

.my-practice-container .modal .modal-content-container .modal-content .modal-header {
    display: flex;
    justify-content: end;
    align-items: center;
}

.my-practice-container .modal .modal-content-container .modal-content .modal-header img{
    cursor: pointer;
    user-select: none;
    
}

</style>